package xyz.ddlnt.servicemg.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xyz.ddlnt.commonutil.exception.GlobalException;
import xyz.ddlnt.commonutil.util.RandomUtil;
import xyz.ddlnt.model.dto.CategoryDTO;
import xyz.ddlnt.model.entity.Category;
import xyz.ddlnt.servicemg.mapper.CategoryMapper;
import xyz.ddlnt.servicemg.service.CategoryService;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author ZZULI_SE 210910
 * @data 2025/4/29 22:27
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    private final CategoryMapper categoryMapper;
    @Override
    public Category saveCategory(String categoryName) {
        Category category =Category.builder()
                .id(RandomUtil.generate12DigitRandomNumber())
                .categoryName(categoryName)
                .createTime(LocalDateTime.now())
                .updateTime(LocalDateTime.now())
                .build();
        int insert = categoryMapper.insert(category);
        if (insert == 0) {
            throw new GlobalException(500, "类别名称已存在");
        }
        return category;
    }

    @Override
    public LocalDateTime updateCategory(CategoryDTO categoryDTO) {
        LocalDateTime updateTime = LocalDateTime.now();
        LambdaUpdateWrapper<Category> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper
                .set(Category::getCategoryName, categoryDTO.getCategoryName())
                .set(Category::getUpdateTime, updateTime)
                .eq(Category::getId, categoryDTO.getId());
        categoryMapper.update(updateWrapper);
        return updateTime;
    }

    @Override
    public List<CategoryDTO> getAllCategoryName() {
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(Category::getId, Category::getCategoryName);
        // 需提供无参构造
        List<Category> categories = categoryMapper.selectList(queryWrapper);
        return categories.stream().map(category -> CategoryDTO.builder()
                .id(category.getId())
                .categoryName(category.getCategoryName())
                .build()).toList();
    }
}
